<script lang="ts" setup>
  import type { Game } from '@/types/game';
  import { ref } from 'vue';
  import dayjs from 'dayjs';
  import { Form, Message } from '@arco-design/web-vue';
  import { mockGame } from '@/api/game';

  const props = defineProps<{
    gameInfo: Game;
  }>();

  const emit = defineEmits(['close']);

  const data = ref({
    dateRange: [props.gameInfo.startDate, props.gameInfo.endDate],
    signDateRange: [props.gameInfo.signStartDate, props.gameInfo.signEndDate],
    playerCount: 100,
  });

  const saving = ref(false);
  const formRef = ref<InstanceType<typeof Form> | null>(null);
  const handleSubmit = async () => {
    if (formRef.value) {
      const validate = await formRef.value.validate();
      if (!validate) {
        try {
          saving.value = true;
          await mockGame({
            gameId: props.gameInfo.id,
            startDate: dayjs(data.value.dateRange[0]).format(
              'YYYY-MM-DD HH:mm:ss'
            ),
            endDate: dayjs(data.value.dateRange[1]).format(
              'YYYY-MM-DD HH:mm:ss'
            ),
            signStartDate: dayjs(data.value.signDateRange[0]).format(
              'YYYY-MM-DD HH:mm:ss'
            ),
            signEndDate: dayjs(data.value.signDateRange[1]).format(
              'YYYY-MM-DD HH:mm:ss'
            ),
            playerCount: data.value.playerCount,
          });
          Message.success('操作成功');
          emit('close');
        } finally {
          saving.value = false;
        }
      }
    }
  };
</script>

<template>
  <a-modal
    title="模拟比赛"
    :width="500"
    visible
    :ok-loading="saving"
    @cancel="emit('close')"
    @before-ok="handleSubmit"
  >
    <a-form ref="formRef" :model="data" layout="vertical">
      <a-form-item
        label="报名时间"
        field="signDateRange"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-range-picker
          v-model="data.signDateRange"
          show-time
          style="width: 400px"
        />
      </a-form-item>

      <a-form-item
        label="比赛时间"
        field="dateRange"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-range-picker v-model="data.dateRange" style="width: 400px" />
      </a-form-item>

      <a-form-item
        label="每场比赛虚拟球员数量"
        field="playerCount"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-input-number
          v-model="data.playerCount"
          :min="1"
          :step="1"
          :precision="0"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
